// pages/lanya/lanya.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    btnClicked: !1
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu();
  },
  onUnload: function () {
    var e = this;
    wx.closeBLEConnection({
      deviceId: e.data.deviceId,
      success: function (e) {
        console.log(e);
      }
    }), wx.closeBluetoothAdapter(function (e) {
      console.log("关闭蓝牙模块" + e);
    });
  },
  // 搜索

  // 连接蓝牙
  bluetoothsave: function () {
    var e = this;
    // 初始化
    wx.openBluetoothAdapter({
      success: function (e) {
        console.log("-----success----------"), console.log(e),                  wx.startBluetoothDevicesDiscovery({ // 状态检测
          services: [],
          success: function (e) {
            console.log("-----startBluetoothDevicesDiscovery--success----------"), console.log(e);
          },
          fail: function (e) {
            console.log(e);
          },
          complete: function (e) {
            console.log(e);
          }
        });
      },
      fail: function (t) {
        console.log("-----fail----------"), console.log(t), wx.showModal({
          title: "提示",
          content: "您的手机蓝牙没有打开,请开启蓝牙\r\n(开启后还是不行？ios13请尝试在系统设置中打开微信APP的蓝牙权限)",
          success: function (t) {
            t.confirm ? (console.log("用户点击确定"), e.bluetoothsave()) : t.cancel && (console.log("用户点击取消"),
              wx.redirectTo({
                url: "../jinrixueya/jinrixueya"
              }));
          }
        });
      },
      complete: function (e) {
        console.log("-----complete----------"), console.log(e);
      }
    }), e.setData({
      timer: setInterval(function () {
        wx.getBluetoothDevices({
          success: function (t) {
            console.log("getBluetoothDevices - success"), console.log(t), e.setData({
              list: t.devices
            }), console.log("list:", e.data.list);
            for (let o in t.devices) {
              if ("" != t.devices[o].deviceId && "LD" == t.devices[o].name) e.toConnPage(t.devices[o])};
          },
          fail: function (e) { },
          complete: function (e) { }
        });
      }, 1e3)
    });
  },

  toConnPage: function (t) {
    var e = this;
    clearTimeout(e.data.timer);
    console.log(t)
    0 == e.data.btnClicked && (e.data.btnClicked = !0, wx.navigateTo({
      url: "../celiang/celiang?deviceId=" + t.deviceId + "&name=" + t.name,
      success: function (e) { },
      fail: function (e) { },
      complete: function (e) { }
    }));
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})